//
//  UserTableViewController.m
//  LWB_Project
//
//  Created by lanou3g on 15/11/11.
//  Copyright © 2015年 wangjianliang. All rights reserved.
//

#import "UserTableViewController.h"
#import "UserFirstTableViewCell.h"
#import "UserSecondTableViewCell.h"
#import "UserThreeTableViewCell.h"
#import "UserFourTableViewCell.h"
#import "UserFiveTableViewCell.h"
#import "XHPathCover.h"
#import "CollectionTableViewController.h"
#import "AboutUserViewController.h"
#import "SDImageCache.h"
#import "UIImageView+WebCache.h"
#import "ReadQRCodeViewController.h"
@interface UserTableViewController ()<UIImagePickerControllerDelegate,UIActionSheetDelegate,UINavigationControllerDelegate>//调用相机相册的时候要遵循的协议

@property (nonatomic, strong) UIView *headerView;

//这个XHPathCover玩意儿就是一个头部视图下拉变大的第三方
@property (nonatomic, strong) XHPathCover *pathCover;

@property (nonatomic, strong) UIImage *contentImage;
@end

@implementation UserTableViewController
static UserSecondTableViewCell *clearCell;


//清除缓存6⃣️
-(void)viewWillAppear:(BOOL)animated
{
   clearCell.clearCacheLable.text =  [self getsizeString:[self getSize]];

}

- (void)viewDidLoad {
    [super viewDidLoad];

//创建二维码扫描的barButtonItem
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-icon(2).png"] style:(UIBarButtonItemStyleDone) target:self action:@selector( TwoDimensionCode:)];
    
#pragma mark-----XHPathCover第三方的使用过程
    _pathCover = [[XHPathCover alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds),CGRectGetHeight(self.view.bounds)/3)];
    [_pathCover setBackgroundImage:[UIImage imageNamed:@"MenuBackground"]];
    
    _pathCover.avatarButton.layer.masksToBounds = YES;
    _pathCover.avatarButton.layer.cornerRadius =  _pathCover.avatarButton.frame.size.height /2;
 
#pragma mark-------就在这吧存入本地的图片拿出来
    //图片存入本地,获取document路径
    NSString *documentStr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    //存到那
    NSString *path = [documentStr stringByAppendingString:@"/userphoto"];
    //拿出来
    NSArray *arr = [NSArray arrayWithContentsOfFile:path];
    //先判断一下，第一次肯定是空
    if (arr == nil)
    {
        //空得话，来一个默认的本地图片
        [_pathCover setAvatarImage:[UIImage imageNamed:@"meicon.png"]];

    }else
    {
        //否则就把存入本低的图片拿出来
        UIImage *image = [UIImage imageWithData:arr[0]];
        [_pathCover setAvatarImage:image];

        }
    
    
    [_pathCover setInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"新闻🐱", XHUserNameKey, @"让新闻更精彩", XHBirthdayKey, nil]];
    self.tableView.tableHeaderView = self.pathCover;
    
    __weak UserTableViewController *wself = self;
    [_pathCover setHandleRefreshEvent:^{
        //下拉效果
        [wself _refreshing];
    }];

#pragma mark-----patchCover自带的有个avatarButton属性
    _pathCover.avatarButton.backgroundColor = [UIColor greenColor];
//自带button的点击方法
    [_pathCover.avatarButton addTarget:self action:@selector(changePicture:) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark-------点击扫一扫键入二维码扫描界面
-(void)TwoDimensionCode:(UIBarButtonItem *)sender
{
    ReadQRCodeViewController *readQRCodeVC = [[ReadQRCodeViewController alloc] init];
    [self showDetailViewController:readQRCodeVC sender:nil];
    
}


#pragma mark-----自带button点击方法的实现
- (void)changePicture:(UIButton *)sender
{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"上传照片吗" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"相机" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        //调用相机的方法，在这调用，下边实现
        [self setImagePickerController:UIImagePickerControllerSourceTypeCamera];
        
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"相册" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        //调用相册的方法，在这调用，下边实现
        [self setImagePickerController:UIImagePickerControllerSourceTypePhotoLibrary];
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
        //没有方法，这就可以为空，不用写
    }];
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    //这一步必须要写，否则的话点击是没有响应的
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark----------相册
-(void)setImagePickerController:(UIImagePickerControllerSourceType )source
{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = source;
    imagePicker.delegate = self;

    [imagePicker setEditing:YES];
    imagePicker.allowsEditing = YES;
    
    //模态推出视图
    [self presentViewController:imagePicker animated:YES completion:nil];

}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    _contentImage = image;
    [_pathCover.avatarButton setBackgroundImage:image forState:(UIControlStateNormal)];


    [_pathCover setAvatarImage:image];
    //要存的东西
    //排除程序崩溃初始化一个默认图片
    NSData *data;
    if (UIImagePNGRepresentation(image) == nil) {
        
        data = UIImageJPEGRepresentation(image, 1);
        
    } else {
        
        data = UIImagePNGRepresentation(image);
    }
    
    //图片存入本地,获取document路径
    NSString *documentStr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    //存到那
    NSString *path = [documentStr stringByAppendingString:@"/userphoto"];
    
    NSArray *arr = @[data];
    //存进去
    [arr writeToFile:path atomically:YES];
//    //拿出来
//    NSData *data1 = [NSData dataWithContentsOfFile:path];
    
   [picker dismissViewControllerAnimated:YES completion:nil];
}




- (void)_refreshing {
    // refresh your data sources
    
    __weak UserTableViewController *wself = self;
    double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [wself.pathCover stopRefresh];
    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark- scroll delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [_pathCover scrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [_pathCover scrollViewDidEndDecelerating:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [_pathCover scrollViewDidEndDragging:scrollView willDecelerate:decelerate];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [_pathCover scrollViewWillBeginDragging:scrollView];
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
 
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
       UITableViewCell *cell;

        switch (indexPath.row)
    {
               case 0:
                  cell = [tableView dequeueReusableCellWithIdentifier:@"userfirstcell" ];
                    if (cell == nil)
                    {
                        cell = [[[NSBundle mainBundle] loadNibNamed:@"UserFirstTableViewCell" owner:self options:nil] firstObject];
                    }
                   break;
               case 1:
                   cell = [tableView dequeueReusableCellWithIdentifier:@"usersecondcell" ];
                    if (cell == nil)
                    {
                        cell = [[[NSBundle mainBundle] loadNibNamed:@"UserSecondTableViewCell" owner:self options:nil] firstObject];
                        clearCell = (UserSecondTableViewCell *) cell;
                        //清除缓存1⃣️
                        clearCell.clearCacheLable.text =  [self getsizeString:[self getSize]];
                    }
                   break;
                case 2:
                    cell = [tableView dequeueReusableCellWithIdentifier:@"userthreecell" ];
                    if (cell == nil)
                    {
                        cell = [[[NSBundle mainBundle] loadNibNamed:@"UserThreeTableViewCell" owner:self options:nil] firstObject];
    
                    }
                    break;


                case 3:
                    cell = [tableView dequeueReusableCellWithIdentifier:@"userfourcell" ];
                    if (cell == nil)
                    {
                        cell = [[[NSBundle mainBundle] loadNibNamed:@"UserFourTableViewCell" owner:self options:nil] firstObject];
                    }

            
                break;
                case 4:
                    cell = [tableView dequeueReusableCellWithIdentifier:@"userfivecell" ];
                    if (cell == nil)
                    {
                        cell = [[[NSBundle mainBundle] loadNibNamed:@"UserFiveTableViewCell" owner:self options:nil] firstObject];
                    }
                    break;
            
                    default:
                            cell = [tableView dequeueReusableCellWithIdentifier:@"userfirstcell"];
                            if (cell == nil)
                            {
                                cell = [[[NSBundle mainBundle] loadNibNamed:@"UserFirstTableViewCell" owner:self options:nil] firstObject];
                            }
                           break;
             }
            
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
            //进入收藏界面
            [self enterCollectionVC];
            break;
           
        case 1:
        //清除缓存
            [self clearCache];
            
            break;
            
        case 2:
            //关于我们
            [self enterAboutUserVC];
            break;
            
            case 3:
            break;
            
            case 4:
            break;
        default:
            break;
    }
}

- (void)enterCollectionVC
{
    CollectionTableViewController *collectVC = [[CollectionTableViewController alloc] init];
    [self.navigationController pushViewController:collectVC animated:YES];
}

//清除缓存2⃣️
-(NSString *)getsizeString:(NSInteger)size
{
    size = [SDImageCache sharedImageCache].getSize;
    if (size > 1024 * 1024) {
        CGFloat floatSize = size / 1024.0 / 1024.0;
        return [NSString stringWithFormat:@"%.fMB",floatSize];
        
    }else if (size > 1024){
        CGFloat floatSize = size / 1024.0;
        return [NSString stringWithFormat:@"%.fKB",floatSize];
    }else if(size > 0)
    {
        return [NSString stringWithFormat:@"%ldKB",size];
    }
 
    return @"0.00KB";
}

- (void)clearCache
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定清除缓存吗" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alertAction1 = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    UIAlertAction *alertAction2 = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        

        //清除缓存3⃣️
        [[SDImageCache sharedImageCache] clearDisk];
        [[SDImageCache sharedImageCache] cleanDisk];
        //显示清除之后的数据
        NSUInteger size = [SDImageCache sharedImageCache].getSize;
        clearCell.clearCacheLable.text =  [self getsizeString:size];
        
    }];

    [alertVC addAction:alertAction1];
    [alertVC addAction:alertAction2];
    [self presentViewController:alertVC animated:YES completion:nil];
}
//清除缓存4⃣️
#pragma mark 获得缓存文件大小
- (float)getSize
{
    return [[SDImageCache sharedImageCache] getSize];
}
//清除缓存⑤
#pragma mark 返回缓存单个文件的大小
- (long long) fileSizeAtPath:(NSString *)filePath {
    
    NSFileManager *manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
        
    }
    
    return 0;
    
}


- (void)enterAboutUserVC
{
    AboutUserViewController *aboutUserVC = [[AboutUserViewController alloc] init];
    [self.navigationController pushViewController:aboutUserVC animated:YES];
}







/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath 
 {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath 
 {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath 
 {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
 {
    // Navigation logic may go here, for example:
    // Create the next view controller.
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];
    
    // Pass the selected object to the new view controller.
    
    // Push the view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
 {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
